import jwt
from datetime import datetime, timedelta

class JwtSsoSdk:
    def __init__(self, secret_key, issuer, audience):
        self.secret_key = secret_key
        self.issuer = issuer
        self.audience = audience

    def generate_token(self, user_id, role_id, name):
        payload = {
            'iss': self.issuer,
            'aud': self.audience,
            'exp': datetime.utcnow() + timedelta(hours=1),
            'iat': datetime.utcnow(),
            'user_id': user_id,
            'role_id': role_id,
            'name': name
        }
        return jwt.encode(payload, self.secret_key, algorithm='HS256')

    def validate_token(self, token):
        try:
            payload = jwt.decode(token, self.secret_key, algorithms=['HS256'],
                                 audience=self.audience, issuer=self.issuer)
            return {
                'user_id': payload['user_id'],
                'role_id': payload['role_id'],
                'name': payload['name']
            }
        except jwt.PyJWTError:
            return None

    def get_token_from_header(self, headers):
        auth_header = headers.get('Authorization')
        if auth_header and auth_header.startswith('Bearer '):
            return auth_header.split(' ')[1]
        return None